//此文件用来定义中间件，引入的这些文件都是封装好的函数，便于中间件的使用
const errorTypes = require("../constants/error-types");
const service = require("../service/user.service");
const md5password = require("../untils/password-handle.js");

//注册用户验证
const verifyUser = async (ctx, next) => {
  //1.获取用户名和密码
  const { name, password } = ctx.request.body;
  console.log(ctx.request.body);

  //2.判断用户名或者密码是否为空
  if (!name || !password) {
    const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
    return ctx.app.emit("error", error, ctx);
  }

  //3.判断这次注册的用户名时没有被注册过的
  const result = await service.getUserByName(name);
  console.log(result);
  if (result.length) {
    const error = new Error(errorTypes.USER_ALREADY_EXISTS);
    return ctx.app.emit("error", error, ctx);
  }

  await next();
};

//加密用户密码
const handlePassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  ctx.request.body.password = md5password(password);

  await next();
};

module.exports = {
  verifyUser,
  handlePassword,
};
